package trb.complexshield.voxel;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;

class Visualisation implements Raytrace.Output {

    public static void main(String[] args) {
        RaytraceApplication.main(args);
    }

    private final VoxelGrid voxelGrid;
    private final int cellSize;
    private final int border = 4;
    final BufferedImage image;
    final Graphics g;

    Visualisation(VoxelGrid voxelGrid, int cellSize) {
        this.voxelGrid = voxelGrid;
        this.cellSize = cellSize;
        image = new BufferedImage((voxelGrid.xdim + border * 2) * cellSize+1
                , (voxelGrid.ydim + border * 2) * cellSize+1, BufferedImage.TYPE_INT_ARGB);
        g = image.getGraphics();
    }

    public void clear(Color color) {
        g.setColor(color);
        g.fillRect(0, 0, image.getWidth(), image.getWidth());
    }

    public void drawGrid(Color color) {
        g.setColor(color);
        for (int i = 0; i <= voxelGrid.ydim; i++) {
            g.drawLine(toInt(0), toInt(i), toInt(voxelGrid.xdim), toInt(i));
        }
        for (int i = 0; i <= voxelGrid.xdim; i++) {
            g.drawLine(toInt(i), toInt(0), toInt(i), toInt(voxelGrid.ydim));
        }
    }

    public void paintVoxelGrid(Color color) {
        g.setColor(color);
        for (int yIdx=0; yIdx<voxelGrid.ydim; yIdx++) {
            for (int xIdx=0; xIdx<voxelGrid.xdim; xIdx++) {
                if (voxelGrid.getBitAtIndex(xIdx, yIdx, voxelGrid.zdim / 2)) {
                    g.fillRect(toInt(xIdx), toInt(yIdx) , cellSize, cellSize);
                }
            }
        }
    }

    public void drawLine(Line line, Color color) {
        g.setColor(color);
        g.drawLine(toInt(line.p1.x), toInt(line.p1.y), toInt(line.p2.x), toInt(line.p2.y));
    }

    int toInt(float coord) {
        return Math.round(coord * cellSize + border * cellSize);
    }

    @Override
    public void addIntersection(Line line, int x, int y, int z, float t) {
        int xcoord = toInt(line.p1.x + t * (line.p2.x-line.p1.x));
        int ycoord = toInt(line.p1.y + t * (line.p2.y-line.p1.y));
        int zcoord = toInt(line.p1.z + t * (line.p2.z-line.p1.z));
        g.setColor(Color.BLACK);
        g.fillRect(xcoord - 3, ycoord - 3, 7, 7);
    }

    @Override
    public void addSegment(Line line, float t1, float t2) {
        System.out.println("addSegment " + t1 + " " + t2);
        int xcoord1 = toInt(line.p1.x + t1 * (line.p2.x-line.p1.x));
        int ycoord1 = toInt(line.p1.y + t1 * (line.p2.y-line.p1.y));
        int xcoord2 = toInt(line.p1.x + t2 * (line.p2.x-line.p1.x));
        int ycoord2 = toInt(line.p1.y + t2 * (line.p2.y-line.p1.y));
        g.setColor(Color.RED);
        g.drawLine(xcoord1, ycoord1, xcoord2, ycoord2);
    }
}
